package com.softWang.job.service;

import com.softWang.job.constants.ScheduleConstants;
import com.softWang.job.util.ScheduleUtils;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

import com.softWang.common.base.BaseServiceMy;
import com.softWang.common.exception.LogicException;
import com.softWang.job.po.JobManage;
import com.softWang.job.mapper.JobManageMapper;
import com.softWang.job.vo.jobManage.*;

/**
 * <p>
 * 定时任务管理---定时任务表 服务实现类
 * </p>
 *
 * @author wang
 * @since 2025-05-08
 */
@Service
public class JobManageService extends BaseServiceMy<JobManage> {

     @Resource
     private JobManageMapper jobManageMapper;
     @Resource
     private Scheduler scheduler;

    /**
     * 项目启动时，初始化定时器
     */
    @PostConstruct
    public void init() throws Exception{
        //scheduler.clear();
        List<JobManage> jobList = jobManageMapper.selectJobAllUnfinished();
        for (JobManage job : jobList)
        {
            boolean exists = scheduler.checkExists(ScheduleUtils.getJobKey(job.getJobId()+""));
            if(!exists) {
                ScheduleUtils.createScheduleJob(scheduler, job);
            }
        }
    }

     /**
     * 分页条件查询
     * @param param
     * @return
     */
     public List<JobManageQueryAllResult> queryall(JobManageQueryAllParam param){
         param.startPage();
         List<JobManageQueryAllResult> results=jobManageMapper.queryall(param);
         return results;
     }

      /**
      * 插入
      * @param param 数据信息
      * @return id
      */
      @Transactional
      public Long add(JobManageAddParam param) throws Exception{

          JobManage entity = new JobManage();
          BeanUtils.copyProperties(param, entity);
          entity.setStatus("0");
          entity.setFinish("0");
          int rows = jobManageMapper.insert(entity);
          if (rows > 0)
          {
              // 判断是否存在
              if (scheduler.checkExists(ScheduleUtils.getJobKey(entity.getJobId()+"")))
              {
                  // 防止创建时存在数据问题 先移除，然后在执行创建操作
                  scheduler.deleteJob(ScheduleUtils.getJobKey(entity.getJobId()+""));
              }
              ScheduleUtils.createScheduleJob(scheduler, entity);
          }
          return entity.getJobId();
      }

      /**
      * 修改
      * @param param  数据信息
      * @return
      */
      @Transactional
      public Long edit(JobManageEditParam param) throws Exception{

         JobManage entity = new JobManage();
         BeanUtils.copyProperties(param, entity);
          int rows = jobManageMapper.updateById(entity);
          if (rows > 0)
          {

              String jobId = entity.getJobId()+"";
              // 判断是否存在
              JobKey jobKey = ScheduleUtils.getJobKey(jobId);
              if (scheduler.checkExists(jobKey))
              {
                  // 防止创建时存在数据问题 先移除，然后在执行创建操作
                  scheduler.deleteJob(jobKey);
              }
              ScheduleUtils.createScheduleJob(scheduler, entity);
          }
         return entity.getJobId();
      }

      /**
      * 获取详情
      * @param id id
      * @return 详情信息
      */
      public JobManage getById(Long id) {
           return jobManageMapper.selectById(id);
      }

      /**
      * 删除部门
      * @param ids 部门id列表
      * @return void
      */
      @Transactional
      public void del(List<Long> ids) throws Exception {
          for (Long id : ids){
              JobManage job = jobManageMapper.selectById(id);
              String jobId = job.getJobId()+"";
              int rows = jobManageMapper.deleteById(jobId);
              if (rows > 0)
              {
                  scheduler.deleteJob(ScheduleUtils.getJobKey(jobId));
              }
          }
      }

      @Transactional
      public void changeStatus(JobManageChangeStatusParam param) throws Exception {
          String status = param.getStatus();
          JobManage job = jobManageMapper.selectById(param.getJobId());
          if (ScheduleConstants.Status.NORMAL.getValue().equals(status))
          {
              resumeJob(job);
          }
          else if (ScheduleConstants.Status.PAUSE.getValue().equals(status))
          {
              pauseJob(job);
          }
      }

    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Transactional(rollbackFor = Exception.class)
    public int pauseJob(JobManage job) throws SchedulerException
    {
        String jobId = job.getJobId()+"";
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobManageMapper.updateById(job);
        if (rows > 0)
        {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId));
        }
        return rows;
    }

    /**
     * 恢复任务
     *
     * @param job 调度信息
     */
    @Transactional(rollbackFor = Exception.class)
    public int resumeJob(JobManage job) throws SchedulerException
    {
        String jobId = job.getJobId()+"";
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = jobManageMapper.updateById(job);
        if (rows > 0)
        {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId));
        }
        return rows;
    }

    public void run(Long id) throws Exception {
        String jobId = id + "";
        scheduler.triggerJob(ScheduleUtils.getJobKey(jobId));
    }
}
